#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdint.h>
#include <string>
#include <memory>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>

const int BUFFERSIZE = 128;
class UdpServer
{
public:
    UdpServer(std::string ip,uint16_t port)
        :_sockfd(-1)
        ,_port(port)
        ,_ip(ip)
    {

    }
    //服务器启动
    void Start()
    {
        char buffer[BUFFERSIZE] = {0};
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t size = recvfrom(_sockfd,buffer,sizeof(buffer) - 1,0,(struct sockaddr*)&peer,&len);
            if(size < 0)
            {
                std::cout << "recvfrom error!!" << std::endl;
            }
            buffer[size] = '\0';
            int port = ntohs(peer.sin_port);
            std::string ip = inet_ntoa(peer.sin_addr);
            //消息打印
            std::cout << ip << ":" << port << "# " << buffer << std::endl;

            std::string echo_msg = "server get!->";
            echo_msg += buffer;
            sendto(_sockfd,echo_msg.c_str(),echo_msg.size(),0,(struct sockaddr*)&peer,len);
        }
    }
    //服务器初始化
    bool InitServer()
    {
        //AF_INET,表明需要网络通信
        //SOCK_DGRAM,面向数据报
        //0，默认，根据第二个参数为面向数据报，自动识别为UDP协议
        _sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd < 0)
        {
            std::cout << "socket create error!!" << std::endl;
            return false;
        }
        std::cout << "socket create success,sockfd : " << _sockfd << std::endl;

        //填充网络通信相关信息
        struct sockaddr_in local;
        memset(&local,'\0',sizeof(struct sockaddr_in));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;//绑定INADDR_ANY

        //绑定
        int ret = bind(_sockfd,(struct sockaddr*)&local,sizeof(struct sockaddr));
        if(ret < 0)
        {
            std::cout << "bind error!!" << std::endl;
            return false;
        }
        std::cout << "bind success " << std::endl;
        return true;
    }
    ~UdpServer()
    {
        if(_sockfd >= 0)
        {
            close(_sockfd);
        }
    }
private:
    int _sockfd;        //文件描述符
    uint16_t _port;     //端口号
    std::string _ip;    //IP地址
};

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " port" << std::endl;
        return 1;
    }
    std::string ip = "47.94.84.249";//本地环回
    uint16_t port = atoi(argv[1]);
    UdpServer* srv = new UdpServer(ip,port);
    srv->InitServer();
    srv->Start();
    return 0;
}